package org.footballmanager.pandafootball.common.util;

import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Slf4j
public class VerifyCodeUtil {
    // 字符数量
    protected static final int LINES = 5;
    // 宽度
    protected static final int WIDTH = 85;
    // 高度
    protected static final int HEIGHT = 25;
    // 字体大小
    protected static final int FONT_SIZE = 20;

    private VerifyCodeUtil() {
    }

    /**
     * 生成随机验证码及图片
     * Object[0]：验证码字符串；
     * Object[1]：验证码图片。
     */
    public static Object[] createImage() {
        // 1.创建空白图片
        BufferedImage image = new BufferedImage(
                WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        // 2.获取图片画笔
        Graphics graphic = image.getGraphics();
        // 3.设置画笔颜色
        graphic.setColor(Color.LIGHT_GRAY);
        // 4.绘制矩形背景
        graphic.fillRect(0, 0, WIDTH, HEIGHT);
        // 5.画随机字符
        Random ran = new Random();
        // 取随机字符索引
        int n1 = ran.nextInt(50);
        int n2 = ran.nextInt(50);
        String sb = n1 + "+" + n2 + "=?";
        // 设置随机颜色
        graphic.setColor(getRandomColor());
        // 设置字体大小
        graphic.setFont(new Font(
                null, Font.BOLD + Font.ITALIC, FONT_SIZE));
        // 画字符
        graphic.drawString(
                sb + "", 0, 25 - 4);
        // 6.画干扰线
        for (int i = 0; i < LINES; i++) {
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 随机画线
            graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
                    ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
        }
        // 7.返回验证码和图片
        return new Object[]{n1 + n2, image};
    }

    /**
     * 随机取色
     */
    public static Color getRandomColor() {
        Random ran = new Random();
        return new Color(ran.nextInt(106), ran.nextInt(206), ran.nextInt(106));
    }

    public static void main(String[] args) throws IOException {
        Object[] objs = createImage();
        log.info(objs[0].toString());
    }
}
